#include <49func.h>
typedef struct shareRes_s {
    int ticket;
    int flag; // 加票事件能否执行的条件 0不可以 1可以
    pthread_mutex_t mutex;
    pthread_cond_t cond;
} shareRes_t;
void *sellWindow1(void *arg){
    shareRes_t * pShareRes = (shareRes_t *)arg;
    while(1){
        pthread_mutex_lock(&pShareRes->mutex);
        if(pShareRes->ticket <= 0){
            pthread_mutex_unlock(&pShareRes->mutex);
            break;
        }
        printf("Before window1 sells ticket, ticket = %d\n", pShareRes->ticket);
        --pShareRes->ticket;
        printf("After window1 sells ticket, ticket = %d\n", pShareRes->ticket);
        if(pShareRes->ticket <= 10){
            pShareRes->flag = 1;
            pthread_cond_signal(&pShareRes->cond);
        }
        pthread_mutex_unlock(&pShareRes->mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}
void *sellWindow2(void *arg){
    shareRes_t * pShareRes = (shareRes_t *)arg;
    while(1){
        pthread_mutex_lock(&pShareRes->mutex);
        if(pShareRes->ticket <= 0){
            pthread_mutex_unlock(&pShareRes->mutex);
            break;
        }
        printf("Before window2 sells ticket, ticket = %d\n", pShareRes->ticket);
        --pShareRes->ticket;
        printf("After window2 sells ticket, ticket = %d\n", pShareRes->ticket);
        if(pShareRes->ticket <= 10){
            pShareRes->flag = 1;
            pthread_cond_signal(&pShareRes->cond);
        }
        pthread_mutex_unlock(&pShareRes->mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}
void * addTicket(void *arg){
    shareRes_t * pShareRes = (shareRes_t *)arg;
    pthread_mutex_lock(&pShareRes->mutex);
    if(pShareRes->flag == 0){
        printf("ticket is enough now!\n");
        pthread_cond_wait(&pShareRes->cond,&pShareRes->mutex);
    }
    printf("ticket is not enough now!\n");
    pShareRes->ticket += 10;
    pthread_mutex_unlock(&pShareRes->mutex);
    pthread_exit(NULL);
}
int main()
{
    shareRes_t shareRes;
    shareRes.ticket = 20;
    shareRes.flag = 0;
    pthread_mutex_init(&shareRes.mutex,NULL);
    pthread_cond_init(&shareRes.cond,NULL);
    pthread_t tid1,tid2,tid3;
    pthread_create(&tid1,NULL,sellWindow1,&shareRes);
    pthread_create(&tid2,NULL,sellWindow2,&shareRes);
    pthread_create(&tid3,NULL,addTicket,&shareRes);
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);
    return 0;
}

